using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Administration;
using System.Xml;
using System.Diagnostics;
using System.IO;

namespace Community.SharePoint.Utilities.Branding
{
    /// <summary>
    /// SharePoint Branding Tool v1.7.5 (Released Code) produced as a courtesy to the SharePoint Community
    /// History: http://www.codeplex.com/BrandingTool for more information
    /// Courtesy from http://sharepointsix.blogspot.com
    /// </summary>
    public partial class BrandingTool : Form
    {
        #region Private Variables
        private List<Dictionary<string, string>> m_availableThemes = new List<Dictionary<string, string>>();

        private DataTable m_dtTable = new DataTable("More Details");
        private int m_x, m_y = 0;

        //Site List
        private List<SPWeb> m_webLists = new List<SPWeb>();
        private MoreDetails m_siteDetails = new MoreDetails();
        #endregion

        #region Public Variables
        //public string InstallationPath
        //{
        //    get { return m_installationPath; }
        //    set { m_installationPath = value; }
        //}
        //private string m_lcid = DEFAULT_LCID;

        //public string Lcid
        //{
        //    get { return m_lcid; }
        //    set { m_lcid = value; }
        //}
        #endregion

        #region Constructors
        public BrandingTool()
        {
            InitializeComponent();
            this.Text = String.Format("{0} v{1}", Properties.Resources.ApplicationTitle, Properties.Resources.Version);
            FillSitesCombo();
            FillAvailableThemes();
        } 
        #endregion

        #region Private Methods
        private void FillSitesCombo()
        {
            try
            {
                if (comboBoxWebApplication.Items.Count > 0)
                {
                    comboBoxWebApplication.Items.Clear();
                    comboBoxWebApplication.Items.Add("Select a site...");
                }
                try
                {
                    SPWebApplicationCollection webApplicationCol = BrandingHelper.GetWebApplicationCollection();
                    comboBoxWebApplication.DisplayMember = "Name";

                    foreach (SPWebApplication webappl in webApplicationCol)
                    {
                        comboBoxWebApplication.Items.Add(webappl);
                    }

                    comboBoxWebApplication.SelectedIndex = 0;
                }
                catch (Exception ex)
                {
                    ShowErrorMessage(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage("Error getting web applications. \n\nDetails: \n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void FillAvailableThemes()
        {
            if (lstThemes.Items.Count > 0)
            {
                lstThemes.Items.Clear();
                m_availableThemes.Clear();
            }
            XmlDocument doc = new XmlDocument();
            string path = BrandingHelper.GetSPThemesXmlPath();
            doc.Load(path);
            //lstThemes.Sorted = true;

            foreach (XmlNode node in doc.DocumentElement.ChildNodes)
            {
                Dictionary<string, string> theme = new Dictionary<string, string>();
                foreach (XmlNode node2 in node.ChildNodes)
                {
                    switch (node2.Name)
                    {
                        case "TemplateID":
                            string templateName = node2.InnerText;
                            theme.Add("ID", templateName);
                            lstThemes.Items.Add(templateName);
                            break;
                        case "DisplayName":
                            string templateDisName = node2.InnerText;
                            theme.Add("DisplayName", templateDisName);
                            break;
                        case "Description":
                            string templateDesc = node2.InnerText;
                            theme.Add("Description", templateDesc);
                            break;
                        case "Thumbnail":
                            string templateNail = node2.InnerText;
                            theme.Add("Thumbnail", templateNail);
                            break;
                        case "Preview":
                            string templateImage = node2.InnerText;
                            theme.Add("Preview", templateImage);
                            break;
                        default:
                            break;
                    }
                }
                m_availableThemes.Add(theme);
            }
        }

        private void FillSiteTemplatesList()
        {
            checkBoxSelectToggleSiteTemplateFilter.Enabled = true;
            checkBoxSelectToggleTargetSites.Enabled = true;

            lstsSiteTemplateFilter.Items.Clear();

            SPWebApplication webappl = (SPWebApplication)comboBoxWebApplication.SelectedItem;
            SPWebTemplateCollection siteTemplateCol = null;
            if (webappl.Sites.Count > 0)
            {
                try
                {
                    siteTemplateCol = BrandingHelper.GetWebTemplates(webappl);
                }
                catch(Exception ex)
                {
                    ShowErrorMessage(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                if (siteTemplateCol != null)
                {
                    lstsSiteTemplateFilter.Sorted = true;

                    operationToolStripProgressBar.Minimum = 0;
                    operationToolStripProgressBar.Maximum = siteTemplateCol.Count + 1;
                    operationToolStripProgressBar.Value = 0;

                    foreach (SPWebTemplate siteTemplate in siteTemplateCol)
                    {
                        operationToolStripProgressBar.Value++;
                        lstsSiteTemplateFilter.Items.Add(String.Format("{0} ({1})", siteTemplate.Name, siteTemplate.Title));
                    }

                    for (int i = 0; i < lstsSiteTemplateFilter.Items.Count; i++)
                    {
                        lstsSiteTemplateFilter.SetItemChecked(i, true);
                    }
                    operationToolStripProgressBar.Value++;
                }
            }
            else
            {
                ShowErrorMessage("No SharePoint sites found on this web application", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            operationToolStripProgressBar.Value = 0;
        }

        private void FillSitesList()
        {
            if (lstsSiteTemplateFilter.CheckedItems.Count > 0)
            {
                List<string> selectedTemplates = new List<string>();
                foreach (int i in lstsSiteTemplateFilter.CheckedIndices)
                {
                    string s = lstsSiteTemplateFilter.Items[i].ToString().Split('#')[0];
                    s = s.ToUpper();
                    selectedTemplates.Add(s);
                }
                SPWebApplication webappl = (SPWebApplication)comboBoxWebApplication.SelectedItem;

                lstSites.Items.Clear();
                m_webLists.Clear();

                operationToolStripProgressBar.Minimum = 0;
                operationToolStripProgressBar.Maximum = webappl.Sites.Count;
                operationToolStripProgressBar.Value = 0;
                foreach (SPSite aSite in webappl.Sites)
                {
                    operationToolStripProgressBar.Value++;
                    if (selectedTemplates.Contains(aSite.RootWeb.WebTemplate))
                    {
                        m_webLists.Add(aSite.RootWeb);
                        lstSites.Items.Add(aSite.RootWeb.ToString() + " (" + aSite.RootWeb.WebTemplate + ")");
                    }
                    FillChildSitesList(selectedTemplates, aSite.RootWeb, aSite.RootWeb.ToString());
                }
            }
            else
            {
                ShowErrorMessage("Please select at least one Site Template to filter", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            operationToolStripProgressBar.Value = 0;
        }

        private void FillChildSitesList(List<string> selectedTemplates, SPWeb web)
        {
            FillChildSitesList(selectedTemplates, web, "");
        }

        private void FillChildSitesList(List<string> selectedTemplates, SPWeb web, string parentNode)
        {
            string nodeName = string.Empty;
            foreach (SPWeb childWeb in web.Webs)
            {
                if (selectedTemplates.Contains(childWeb.WebTemplate.ToUpper()))
                {
                    m_webLists.Add(childWeb);
                    nodeName = (parentNode.Length == 0) ? (childWeb.ToString() + " (" + childWeb.WebTemplate + ")") : ("" + parentNode + "\\" + childWeb.ToString() + " (" + childWeb.WebTemplate + ")");
                    lstSites.Items.Add(nodeName);
                }
                FillChildSitesList(selectedTemplates, childWeb, parentNode + "\\" + childWeb.ToString());
            }
        }

        private void ApplyTheme()
        {
            operationToolStripDropDownButton.Image = Community.SharePoint.Utilities.Branding.Properties.Resources.Info;
            string status = "Updating Theme... ";
            operationToolStripDropDownButton.Text = status;
            this.Refresh();

            string originaltheme = string.Empty;
            //Apply selected theme in ListView1 to the checked sites.
            if (lstSites.CheckedItems.Count <= 0)
            {
                ShowErrorMessage("No site was selected", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                operationToolStripDropDownButton.Text = "Ready ";
                operationToolStripDropDownButton.Image = Community.SharePoint.Utilities.Branding.Properties.Resources.Info;
                return;
            }
            if (lstThemes.SelectedIndex == -1)
            {
                ShowErrorMessage("No theme was selected", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                operationToolStripDropDownButton.Text = "Ready ";
                operationToolStripDropDownButton.Image = Community.SharePoint.Utilities.Branding.Properties.Resources.Info;
                return;
            }

            string themaName = (string)lstThemes.SelectedItem;

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                operationToolStripProgressBar.Minimum = 0;
                operationToolStripProgressBar.Maximum = lstSites.Items.Count;
                operationToolStripProgressBar.Value = 0;
                for (int i = 0; i < lstSites.Items.Count; i++)
                {
                    operationToolStripProgressBar.Value = i + 1;

                    if (lstSites.GetItemChecked(i))
                    {
                        SPWeb web = m_webLists[i];
                        BrandingHelper.WriteToLog(String.Format("Processing site collection '{0}' with url: '{1}'", web.Title, web.Url));
                        originaltheme = web.Theme;
                        web.AllowUnsafeUpdates = true;
                        web.ApplyTheme(themaName);
                        web.Update();
                        BrandingHelper.WriteToLog(String.Format("Updated Theme from '{0}' to '{1}'", originaltheme, web.Theme));
                        //if (checkBoxIncludeAllChildSites.Checked)
                        //{
                        //    ApplyThemeToChild(web, themaName);
                        //}
                        web.AllowUnsafeUpdates = false;

                    }
                }
                operationToolStripProgressBar.Value = 0;
                ShowOperationComplete("Theme application complete.", true);
            }
            catch (Exception ex)
            {
                BrandingHelper.WriteToLog("Error: " + ex.ToString());
                ShowErrorMessage("Error: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                operationToolStripProgressBar.Value = 0;
                ShowOperationComplete("Error: " + ex.Message, true);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        private void ReapplyTheme()
        {
            #region Get Selected Theme
            operationToolStripDropDownButton.Image = Community.SharePoint.Utilities.Branding.Properties.Resources.Info;
            string status = "Updating Theme... ";
            operationToolStripDropDownButton.Text = status;
            this.Refresh();

            string originaltheme = string.Empty;
            //Apply selected theme in ListView1 to the checked sites.
            if (lstSites.CheckedItems.Count <= 0)
            {
                ShowErrorMessage("No site was selected", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                operationToolStripDropDownButton.Text = "Ready ";
                operationToolStripDropDownButton.Image = Community.SharePoint.Utilities.Branding.Properties.Resources.Info;
                return;
            }
            if (lstThemes.SelectedIndex == -1)
            {
                ShowErrorMessage("No theme was selected", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                operationToolStripDropDownButton.Text = "Ready ";
                operationToolStripDropDownButton.Image = Community.SharePoint.Utilities.Branding.Properties.Resources.Info;
                return;
            }

            string themaName = (string)lstThemes.SelectedItem; 
            #endregion

            #region Apply Default Theme
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                operationToolStripProgressBar.Minimum = 0;
                operationToolStripProgressBar.Maximum = lstSites.Items.Count * 2;
                operationToolStripProgressBar.Value = 0;
                for (int i = 0; i < lstSites.Items.Count; i++)
                {
                    operationToolStripProgressBar.Value = i + 1;

                    if (lstSites.GetItemChecked(i))
                    {
                        SPWeb web = m_webLists[i];
                        BrandingHelper.WriteToLog(String.Format("Reapply theme: Processing site collection '{0}' with url: '{1}'", web.Title, web.Url));
                        originaltheme = web.Theme;
                        web.AllowUnsafeUpdates = true;
                        web.ApplyTheme(BrandingHelper.NONE_THEME);
                        web.Update();
                        BrandingHelper.WriteToLog(String.Format("Reapply theme: Updated Theme from '{0}' to '{1}'", originaltheme, web.Theme));
                        web.AllowUnsafeUpdates = false;
                    }
                }
            }
            catch (Exception ex)
            {
                BrandingHelper.WriteToLog("Error: " + ex.ToString());
                ShowErrorMessage("Error: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                operationToolStripProgressBar.Value = 0;
                ShowOperationComplete("Error: " + ex.Message, true);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
            #endregion

            #region Recycle Application Pool
            SPWebApplication currentAppPool = (SPWebApplication)comboBoxWebApplication.SelectedItem;
            try
            {
                BrandingHelper.RecycleApplicationPool(currentAppPool.ApplicationPool.Name);
                BrandingHelper.WriteToLog(String.Format("Reapply theme: Recycled Application Pool - '{0}'", currentAppPool.ApplicationPool.Name));
            }
            catch (Exception ex)
            {
                ShowErrorMessage("Error recycling application pool", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            #endregion

            #region Apply New Theme
            try
            {
                Cursor.Current = Cursors.WaitCursor;

                for (int i = 0; i < lstSites.Items.Count; i++)
                {
                    operationToolStripProgressBar.Value = i + 1;

                    if (lstSites.GetItemChecked(i))
                    {
                        SPWeb web = m_webLists[i];
                        BrandingHelper.WriteToLog(String.Format("Processing site collection '{0}' with url: '{1}'", web.Title, web.Url));
                        originaltheme = web.Theme;
                        web.AllowUnsafeUpdates = true;
                        web.ApplyTheme(themaName);
                        web.Update();
                        BrandingHelper.WriteToLog(String.Format("Updated Theme from '{0}' to '{1}'", originaltheme, web.Theme));
                        web.AllowUnsafeUpdates = false;
                    }
                }
                operationToolStripProgressBar.Value = 0;
                ShowOperationComplete("Theme application complete.", true);
            }
            catch (Exception ex)
            {
                BrandingHelper.WriteToLog("Error: " + ex.ToString());
                ShowErrorMessage("Error: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                operationToolStripProgressBar.Value = 0;
                ShowOperationComplete("Error: " + ex.Message, true);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            } 
            #endregion
        }        

        private void UpdateSiteProperties()
        {
            //Apply selected site properties in ListView1 to the checked sites.
            if (lstSites.CheckedItems.Count <= 0)
            {
                ShowErrorMessage("No site was selected", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            try
            {
                Cursor.Current = Cursors.WaitCursor;
                string status = "Updating Properties... ";
                operationToolStripDropDownButton.Text = status;
                this.Refresh();

                operationToolStripProgressBar.Minimum = 0;
                operationToolStripProgressBar.Maximum = lstSites.Items.Count;
                operationToolStripProgressBar.Value = 0;
                for (int i = 0; i < lstSites.Items.Count; i++)
                {
                    operationToolStripProgressBar.Value = i + 1;

                    if (lstSites.GetItemChecked(i))
                    {
                        SPWeb web = m_webLists[i];

                        BrandingHelper.WriteToLog(String.Format("Processing site collection '{0}' with url: '{1}'", web.Title, web.Url));
                        web.AllowUnsafeUpdates = true;
                        if (checkBoxMasterUrl.Checked)
                        {
                            web.MasterUrl = textBoxMasterUrl.Text;
                            BrandingHelper.WriteToLog(String.Format("Change MasterUrl from '{0}' to '{1}'", web.MasterUrl, textBoxMasterUrl.Text));
                        }
                        if (checkBoxCustomMasterUrl.Checked)
                        {
                            web.CustomMasterUrl = textBoxCustomMasterUrl.Text;
                            BrandingHelper.WriteToLog(String.Format("Change CustomMasterUrl from '{0}' to '{1}'", web.CustomMasterUrl, textBoxCustomMasterUrl.Text));
                        }
                        if (checkBoxSiteLogoUrl.Checked)
                        {
                            web.SiteLogoUrl = textBoxSiteLogoUrl.Text;
                            BrandingHelper.WriteToLog(String.Format("Change SiteLogoUrl from '{0}' to '{1}'", web.SiteLogoUrl, textBoxSiteLogoUrl.Text));
                        }
                        if (checkBoxSiteLogoDescription.Checked)
                        {
                            web.SiteLogoDescription = textBoxSiteLogoDescription.Text;
                            BrandingHelper.WriteToLog(String.Format("Change SiteLogoDescription from '{0}' to '{1}'", web.SiteLogoDescription, textBoxSiteLogoDescription.Text));
                        }
                        if (checkBoxAlternateCssUrl.Checked)
                        {
                            web.AlternateCssUrl = textBoxAlternateCssUrl.Text;
                            BrandingHelper.WriteToLog(String.Format("Change AlternateCssUrl from '{0}' to '{1}'", web.AlternateCssUrl, textBoxAlternateCssUrl.Text));
                        }
                        web.Update();
                        BrandingHelper.WriteToLog(String.Format("Updated changes for site: '{0}' at '{1}'", web.Title, web.Url));

                        //if (checkBoxIncludeAllChildSites.Checked)
                        //{
                        //    UpdateSitePropertiesToChild(web);
                        //}

                        web.AllowUnsafeUpdates = false;
                    }
                }
                operationToolStripProgressBar.Value = 0;
                ShowOperationComplete("Status: Site properties update completed", true);
            }
            catch (Exception ex)
            {
                BrandingHelper.WriteToLog("Error: " + ex.ToString());
                ShowErrorMessage("Error: " + ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
                operationToolStripProgressBar.Value = 0;
                ShowOperationComplete("Error: " + ex.Message, true);
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        //private void UpdateSitePropertiesToChild(SPWeb web)
        //{
        //    foreach (SPWeb childweb in web.Webs)
        //    {
        //        bool currAllowUnsafeUpdates = childweb.AllowUnsafeUpdates;
        //        childweb.AllowUnsafeUpdates = true;

        //        BrandingHelper.WriteToLog(String.Format("Processing child site '{0}' with url: '{1}'", childweb.Title, childweb.Url));

        //        if (_upWindow.UpdateMasterUrl)
        //        {
        //            childweb.MasterUrl = _upWindow.MasterUrl;
        //            BrandingHelper.WriteToLog(String.Format("Change MasterUrl from '{0}' to '{1}'", childweb.MasterUrl, _upWindow.MasterUrl));
        //        }
        //        if (_upWindow.UpdateCustomMasterUrl)
        //        {
        //            childweb.CustomMasterUrl = _upWindow.CustomMasterUrl;
        //            BrandingHelper.WriteToLog(String.Format("Change CustomMasterUrl from '{0}' to '{1}'", childweb.CustomMasterUrl, _upWindow.CustomMasterUrl));
        //        }
        //        if (_upWindow.UpdateSiteLogoUrl)
        //        {
        //            childweb.SiteLogoUrl = _upWindow.SiteLogoUrl;
        //            BrandingHelper.WriteToLog(String.Format("Change SiteLogoUrl from '{0}' to '{1}'", childweb.SiteLogoUrl, _upWindow.SiteLogoUrl));
        //        }
        //        if (_upWindow.UpdateSiteLogoDescription)
        //        {
        //            childweb.SiteLogoDescription = _upWindow.SiteLogoDescription;
        //            BrandingHelper.WriteToLog(String.Format("Change SiteLogoDescription from '{0}' to '{1}'", childweb.SiteLogoDescription, _upWindow.SiteLogoDescription));
        //        }

        //        childweb.Update();
        //        BrandingHelper.WriteToLog("Updates Applied");

        //        childweb.AllowUnsafeUpdates = currAllowUnsafeUpdates;
        //        UpdateSitePropertiesToChild(childweb);
        //    }
        //}

        private bool CheckSitesSelected()
        {
            if (lstSites.CheckedItems.Count <= 0)
            {
                ShowErrorMessage("Please select the Sites where changes are to be applied before proceeding", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return false;
            }
            else
            {
                return true;
            }
        }

        private static DialogResult ShowErrorMessage(string message, string title, MessageBoxButtons buttons, MessageBoxIcon icon)
        {
            return MessageBox.Show(message, title, buttons, icon, MessageBoxDefaultButton.Button1);
        }

        private void ShowOperationComplete(string message, bool success)
        {
            operationToolStripDropDownButton.Text = (success) ? "Operation Complete " : "Operation Failed ";
            operationToolStripDropDownButton.Image = (success) ? Community.SharePoint.Utilities.Branding.Properties.Resources.Success : Community.SharePoint.Utilities.Branding.Properties.Resources.Error;

            try
            {
                operationToolStripDropDownButton.DropDownItems.RemoveAt(0);
            }
            catch 
            {
            }
            Bitmap _statusIcon = (success) ? Community.SharePoint.Utilities.Branding.Properties.Resources.Success : Community.SharePoint.Utilities.Branding.Properties.Resources.Error;
            string _statusDetail = "Status: " + message;
            operationToolStripDropDownButton.DropDownItems.Add(_statusDetail, _statusIcon, viewLogToolStripMenuItem_Click);

        }

        private void ViewLog()
        {
            string path = BrandingHelper.GetTempPath() + String.Format("BrandingTool{0}-{1}-{2}.txt", DateTime.Now.Day.ToString(), DateTime.Now.Month.ToString(), DateTime.Now.Year.ToString());
            if (File.Exists(path))
            {
                ProcessStartInfo procInfo = new ProcessStartInfo(path);
                Process.Start(procInfo);
            }
            else
                ShowErrorMessage("Log is not yet generated. Logs are only generated after an operation is complete.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        #endregion

        #region UI Events
        private void buttonOpenWebApp_Click(object sender, EventArgs e)
        {
            if (comboBoxWebApplication.SelectedIndex > 0)
            {
                FillSiteTemplatesList();
                FillSitesList();
            }
            else
            {
                ShowErrorMessage("Please select an available web application to begin", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {

            Community.SharePoint.Utilities.Branding.Properties.Settings.Default.Save();
        }

        private void btnSelectAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < lstSites.Items.Count; i++)
            {
                lstSites.SetItemChecked(i, true);
            }
        }

        private void btnUnselectAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < lstSites.Items.Count; i++)
            {
                lstSites.SetItemChecked(i, false);
            }
        }

        private void lstSites_SelectedIndexChanged(object sender, EventArgs e)
        {
            //FillSiteTemplatesList();

            int index = lstSites.SelectedIndex;
            if (index != -1)
            {

                SPWeb web = m_webLists[index];
                m_dtTable = new DataTable("Site Details");
                m_dtTable.Columns.Add("Property");
                m_dtTable.Columns.Add("Value");
                m_dtTable.Rows.Add("Title", web.Title);
                m_dtTable.Rows.Add("Name", web.Name);
                m_dtTable.Rows.Add("URL", web.Url);
                m_dtTable.Rows.Add("Description", web.Description);
                m_dtTable.Rows.Add("MasterUrl", web.MasterUrl);
                m_dtTable.Rows.Add("CustomMasterUrl", web.CustomMasterUrl);
                m_dtTable.Rows.Add("SiteLogoUrl", web.SiteLogoUrl);
                m_dtTable.Rows.Add("SiteLogoDescription", web.SiteLogoDescription);
                m_dtTable.Rows.Add("Theme", web.Theme);
                m_dtTable.Rows.Add("ThemeCssUrl", web.ThemeCssUrl);
                m_dtTable.Rows.Add("AlternateCssUrl", web.AlternateCssUrl);
                m_dtTable.Rows.Add("WebTemplate", web.WebTemplate);
                m_dtTable.Rows.Add("WebTemplateId", web.WebTemplateId.ToString());
                m_dtTable.Rows.Add("RootFolder", web.RootFolder.ToString());
                m_dtTable.Rows.Add("PortalName", web.PortalName);
                m_dtTable.Rows.Add("PortalUrl", web.PortalUrl);
                m_dtTable.Rows.Add("Language", web.Language.ToString());
                m_dtTable.Rows.Add("Author", web.Author);
                m_dtTable.Rows.Add("Number of SubSites", web.Webs.Count.ToString());
                m_dtTable.Rows.Add("IsRootWeb", web.IsRootWeb.ToString());
                try
                {
                    m_dtTable.Rows.Add("ParentWeb.Name", web.ParentWeb.Name);
                    m_dtTable.Rows.Add("ParentWeb.Title", web.ParentWeb.Title);
                }
                catch { }
                this.dataGridViewDetails.DataSource = m_dtTable;
                this.dataGridViewDetails.Update();
                this.buttonDetails.Text = "&" + m_dtTable.TableName;
            }
        }

        private void buttonFilter_Click(object sender, EventArgs e)
        {
            FillSitesList();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            About abt = new About();
            abt.ShowDialog();
        }

        private void webApplicationsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FillSitesCombo();
        }

        private void availableThemesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FillAvailableThemes();
        }

        private void filterToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FillSitesList();
        }

        private void sitesToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            if (comboBoxWebApplication.SelectedIndex > 0)
            {
                FillSiteTemplatesList();
                FillSitesList();
            }
            else
            {
                ShowErrorMessage("Please select an available site", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void siteTemplatesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (comboBoxWebApplication.SelectedIndex > 0)
            {
                FillSiteTemplatesList();
                FillSitesList();
            }
            else
            {
                ShowErrorMessage("Please select an available site", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void applyThemeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlBranding.SelectedTab = tabPageThemesSelection;
            ApplyTheme();
        }

        private void checkBoxSelectToggleSiteTemplateFilter_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxSelectToggleSiteTemplateFilter.Checked)
            {
                for (int i = 0; i < lstsSiteTemplateFilter.Items.Count; i++)
                {
                    lstsSiteTemplateFilter.SetItemChecked(i, true);
                }
                checkBoxSelectToggleSiteTemplateFilter.Text = "Select None";
            }
            else
            {
                for (int i = 0; i < lstsSiteTemplateFilter.Items.Count; i++)
                {
                    lstsSiteTemplateFilter.SetItemChecked(i, false);
                }
                checkBoxSelectToggleSiteTemplateFilter.Text = "Select All";
            }
        }

        private void checkBoxSelectToggleTargetSites_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxSelectToggleTargetSites.Checked)
            {
                for (int i = 0; i < lstSites.Items.Count; i++)
                {
                    lstSites.SetItemChecked(i, true);
                }
                checkBoxSelectToggleTargetSites.Text = "Select None";
            }
            else
            {
                for (int i = 0; i < lstSites.Items.Count; i++)
                {
                    lstSites.SetItemChecked(i, false);
                }
                checkBoxSelectToggleTargetSites.Text = "Select All";
            }
        }

        private void updateMasterUrlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlBranding.SelectedTab = tabPageBrandingProperties;
            checkBoxMasterUrl.Checked = true;
        }

        private void updateCustomMasterUrlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlBranding.SelectedTab = tabPageBrandingProperties;
            checkBoxCustomMasterUrl.Checked = true;
        }

        private void updateSiteLogoUrlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlBranding.SelectedTab = tabPageBrandingProperties;
            checkBoxSiteLogoUrl.Checked = true;
        }

        private void updateSiteLogoDescriptionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlBranding.SelectedTab = tabPageBrandingProperties;
            checkBoxSiteLogoDescription.Checked = true;
        }

        private void buttonApplyTheme_Click(object sender, EventArgs e)
        {
            ApplyTheme();
        }

        private void logToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ViewLog();            
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            int index;
            if ((m_x != 0) && (m_y != 0))
            {
                index = lstSites.IndexFromPoint(m_x, m_y);
                if (index != -1)
                {

                    SPWeb web = m_webLists[index];
                    m_dtTable = new DataTable("Site Details");
                    m_dtTable.Columns.Add("Property");
                    m_dtTable.Columns.Add("Value");
                    m_dtTable.Rows.Add("Title", web.Title);
                    m_dtTable.Rows.Add("Name", web.Name);
                    m_dtTable.Rows.Add("URL", web.Url);
                    m_dtTable.Rows.Add("Description", web.Description);
                    m_dtTable.Rows.Add("MasterUrl", web.MasterUrl);
                    m_dtTable.Rows.Add("CustomMasterUrl", web.CustomMasterUrl);
                    m_dtTable.Rows.Add("SiteLogoUrl", web.SiteLogoUrl);
                    m_dtTable.Rows.Add("SiteLogoDescription", web.SiteLogoDescription);
                    m_dtTable.Rows.Add("Theme", web.Theme);
                    m_dtTable.Rows.Add("ThemeCssUrl", web.ThemeCssUrl);
                    m_dtTable.Rows.Add("AlternateCssUrl", web.AlternateCssUrl);
                    m_dtTable.Rows.Add("WebTemplate", web.WebTemplate);
                    m_dtTable.Rows.Add("WebTemplateId", web.WebTemplateId.ToString());
                    m_dtTable.Rows.Add("RootFolder", web.RootFolder.ToString());
                    m_dtTable.Rows.Add("PortalName", web.PortalName);
                    m_dtTable.Rows.Add("PortalUrl", web.PortalUrl);
                    m_dtTable.Rows.Add("Language", web.Language.ToString());
                    m_dtTable.Rows.Add("Author", web.Author);
                    m_dtTable.Rows.Add("Number of SubSites", web.Webs.Count.ToString());
                    m_dtTable.Rows.Add("IsRootWeb", web.IsRootWeb.ToString());
                    try
                    {
                        m_dtTable.Rows.Add("ParentWeb.Name", web.ParentWeb.Name);
                        m_dtTable.Rows.Add("ParentWeb.Title", web.ParentWeb.Title);
                    }
                    catch { }
                    m_siteDetails.AddProperties(m_dtTable);
                    m_siteDetails.ShowDialog();
                    this.buttonDetails.Text = "&" + m_dtTable.TableName;
                }
            }
        }

        private void lstSites_MouseUp(object sender, MouseEventArgs e)
        {
            m_x = e.X;
            m_y = e.Y;
            int index;

            if ((m_x != 0) && (m_y != 0))
            {
                index = lstSites.IndexFromPoint(m_x, m_y);
                if (index != -1)
                {
                    lstSites.SelectedIndex = index;
                }
            }
        }

        private void lstThemes_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lstThemes.SelectedIndex >= 0)
            {
                //Set image preview
                string themaName = (string)lstThemes.SelectedItem;

                try
                {
                    string endPath = string.Empty;
                    endPath = m_availableThemes[lstThemes.SelectedIndex]["Preview"];//themePreviews[lstThemes.SelectedIndex];

                    if (endPath.Length > 0)
                    {
                        string imgPath = BrandingHelper.InstallationPath + @"TEMPLATE\" + endPath;
                        pictureBox1.ImageLocation = imgPath;
                        this.pictureBox1.Cursor = System.Windows.Forms.Cursors.Hand;
                    }

                }
                catch { }

                // add info about theme
                m_dtTable = new DataTable("Theme Details");
                m_dtTable.Columns.Add("Properties");
                m_dtTable.Columns.Add("Values");
                m_dtTable.Rows.Add("DisplayName", m_availableThemes[lstThemes.SelectedIndex]["DisplayName"]);
                m_dtTable.Rows.Add("TemplateID", m_availableThemes[lstThemes.SelectedIndex]["ID"]);
                m_dtTable.Rows.Add("Description", m_availableThemes[lstThemes.SelectedIndex]["Description"]);
                m_dtTable.Rows.Add("Thumbnail", m_availableThemes[lstThemes.SelectedIndex]["Thumbnail"]);
                m_dtTable.Rows.Add("Preview", m_availableThemes[lstThemes.SelectedIndex]["Preview"]);
                dataGridViewDetails.DataSource = m_dtTable;
                dataGridViewDetails.Update();
                this.buttonDetails.Text = "&" + m_dtTable.TableName;

            }

        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (lstThemes.SelectedIndex >= 0)
            {
                string themaName = (string)lstThemes.SelectedItem;
                string endPath = string.Empty;
                try
                {
                    endPath = m_availableThemes[lstThemes.SelectedIndex]["Preview"];//themePreviews[lstThemes.SelectedIndex];
                }
                catch { }
                if (endPath.Length > 0)
                {
                    string imgPath = Path.Combine(BrandingHelper.InstallationPath + @"TEMPLATE\", endPath.Replace('/', '\\'));
                    Process proc = new Process();
                    proc.StartInfo.FileName = "explorer.exe";
                    proc.StartInfo.Arguments = imgPath;
                    proc.Start();

                }
            }

        }

        private void buttonDetails_Click(object sender, EventArgs e)
        {
            m_siteDetails.AddProperties(m_dtTable);
            m_siteDetails.ShowDialog();
        }

        private void openSiteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                int index;

                if ((m_x != 0) && (m_y != 0))
                {
                    index = lstSites.IndexFromPoint(m_x, m_y);
                    if (index != -1)
                    {
                        SPWeb web = m_webLists[index];

                        string Url = web.Url;

                        if (Url.Length > 0)
                        {
                            Process proc = new Process();
                            proc.StartInfo.FileName = "iexplore.exe";
                            proc.StartInfo.Arguments = Url;
                            proc.Start();
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage("Error opening site. " + ex.ToString(), "Open Site", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void buttonApplyProperties_Click(object sender, EventArgs e)
        {
            //Validation
            if ((checkBoxMasterUrl.Checked) && (textBoxMasterUrl.Text.Length == 0))
            {
                ShowErrorMessage("Please enter a value for the Master Page URL", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if ((checkBoxCustomMasterUrl.Checked) && (textBoxCustomMasterUrl.Text.Length == 0))
            {
                ShowErrorMessage("Please enter a value for the Custom Master (Application) Page URL", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if ((checkBoxSiteLogoUrl.Checked) && (textBoxSiteLogoUrl.Text.Length == 0))
            {
                ShowErrorMessage("Please enter a value for the Site Logo URL", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            if ((checkBoxSiteLogoDescription.Checked) && (textBoxSiteLogoDescription.Text.Length == 0))
            {
                if (ShowErrorMessage("Site Logo Description value is blank. Proceed?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    return;
                }
            }
            if ((checkBoxAlternateCssUrl.Checked) && (textBoxAlternateCssUrl.Text.Length == 0))
            {
                if (ShowErrorMessage("Alternate CSS Url value is blank. Proceed?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
                {
                    return;
                }
            }

            if ((checkBoxMasterUrl.Checked) || (checkBoxCustomMasterUrl.Checked) || (checkBoxSiteLogoUrl.Checked) || (checkBoxSiteLogoDescription.Checked) || (checkBoxAlternateCssUrl.Checked))
            {
                //Update
                UpdateSiteProperties();
            }
            else
            {
                ShowErrorMessage("No properties were updated. Please tick the corresponding checkbox to update the property", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        private void themesFolderToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            string themesFolderPath = BrandingHelper.InstallationPath + @"TEMPLATES\THEMES\";
            ProcessStartInfo proc = new ProcessStartInfo(themesFolderPath);
            Process.Start(proc);
        }

        private void folderToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            string themesFolderPath = BrandingHelper.InstallationPath;
            ProcessStartInfo proc = new ProcessStartInfo(themesFolderPath);
            Process.Start(proc);
        }

        private void sPThemesxmlToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string xmlFilePath = BrandingHelper.InstallationPath + @"TEMPLATE\LAYOUTS\1033\SPTHEMES.XML";

            if (ShowErrorMessage("Should the file be backed up before editing?", "Back up file", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                string backupfilename = BrandingHelper.InstallationPath + @"TEMPLATE\LAYOUTS\1033\SPTHEMES" + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + "_" + DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year.ToString() + ".XML";
                if (File.Exists(backupfilename))
                {
                    if (ShowErrorMessage("File already exists. Overwrite existing backup file?", "File Exists", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        //If overwrite
                        //delete old file
                        File.Delete(backupfilename);
                    }
                }
                File.Copy(xmlFilePath, backupfilename);
            }

            Process proc = new Process();
            proc.StartInfo.FileName = "notepad.exe";
            proc.StartInfo.Arguments = xmlFilePath;
            proc.Start();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void readmetxtToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "notepad.exe";
            proc.StartInfo.Arguments = Environment.CurrentDirectory + "\\readme.txt";
            proc.Start();
        }

        private void changeMasterPageSettingsInSharePointToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                int index;

                if ((m_x != 0) && (m_y != 0))
                {
                    index = lstSites.IndexFromPoint(m_x, m_y);
                    if (index != -1)
                    {
                        SPWeb web = m_webLists[index];

                        string Url = web.Url;

                        if (Url.Length > 0)
                        {
                            Process proc = new Process();
                            proc.StartInfo.FileName = "iexplore.exe";
                            proc.StartInfo.Arguments = Url + @"/_Layouts/ChangeSiteMasterPage.aspx";
                            proc.Start();
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage("Error opening site. " + ex.ToString(), "Open Site", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void changeSiteThemeInSharePointToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                int index;

                if ((m_x != 0) && (m_y != 0))
                {
                    index = lstSites.IndexFromPoint(m_x, m_y);
                    if (index != -1)
                    {
                        SPWeb web = m_webLists[index];

                        string Url = web.Url;

                        if (Url.Length > 0)
                        {
                            Process proc = new Process();
                            proc.StartInfo.FileName = "iexplore.exe";
                            proc.StartInfo.Arguments = Url + @"/_layouts/themeweb.aspx";
                            proc.Start();
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage("Error opening site. " + ex.ToString(), "Open Site", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void browseTheMasterPageGalleryToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                int index;

                if ((m_x != 0) && (m_y != 0))
                {
                    index = lstSites.IndexFromPoint(m_x, m_y);
                    if (index != -1)
                    {
                        SPWeb web = m_webLists[index];

                        string Url = web.Url;

                        if (Url.Length > 0)
                        {
                            Process proc = new Process();
                            proc.StartInfo.FileName = "iexplore.exe";
                            proc.StartInfo.Arguments = Url + @"/_catalogs/masterpage/Forms/AllItems.aspx";
                            proc.Start();
                        }
                    }

                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage("Error opening site. " + ex.ToString(), "Open Site", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        } 

        private void viewLogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ViewLog();
        }

        private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Options optionsWindow = new Options();
            optionsWindow.ShowDialog(this);
        }

        private void toolStripStatusLabel1_Click(object sender, EventArgs e)
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "iexplore.exe";
            proc.StartInfo.Arguments = Properties.Resources.Blog1;
            proc.Start();
        }

        private void toolStripStatusLabel3_Click(object sender, EventArgs e)
        {
            Process proc = new Process();
            proc.StartInfo.FileName = "iexplore.exe";
            proc.StartInfo.Arguments = Properties.Resources.Codeplex;
            proc.Start();
        }

        private void toolRequirementsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Information about SharePoint Branding Tool v." + Properties.Resources.Version + ". \n\nYou will need to run this tool:\n1. On the SharePoint server where you are applying the changes\n2. With a user account that has privileges to update Themes and Site properties\n3.* With English version of SharePoint installed by default. \n\nNote: *You will need to modify the configuration file for other language versions to work. \n\nFor more information visit:\nhttp://www.codeplex.com/BrandingTool\nhttp://sharepointsix.blogspot.com", "SharePoint Branding Tool v." + Properties.Resources.Version, MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
        #endregion

        private void buttonReapply_Click(object sender, EventArgs e)
        {
            if (ShowErrorMessage("This will recycle the application pool for the web application. Proceed?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                ReapplyTheme();
                FillAvailableThemes();
            }
        }

        private void recycleApplicationPoolToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AppPoolSelection AppPoolSelectionWindow = new AppPoolSelection();
            AppPoolSelectionWindow.ShowDialog();   
        }
    }
}